package cn.com.wxd.amumu.configcenter.ctl;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.util.Properties;

import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * Title:
 * Description:
 * <p>
 * Company: Amumu系统
 * Copyright: Copyright (c) 2017
 * All right reserved.
 * Created by WangXuDong on 2017/8/21.
 *
 * @author WangXuDong
 * @version 1.0
 */
@Controller
@RequestMapping("/")
public class ConfigCenterCtl {

    @RequestMapping("/root")
    public void fetchConfig(@RequestParam("filename") String fileName,
                            HttpServletResponse response) throws IOException {
        if (fileName == null || fileName.isEmpty()) {
            return;
        }
        File file = ResourceUtils.getFile("classpath:" + fileName);
        InputStream in = new BufferedInputStream(new FileInputStream(file));
        response.setContentType("application/octet-stream");
        OutputStream stream = response.getOutputStream();
        response.setCharacterEncoding("UTF-8");
        byte[] buff = new byte[1024 * 4];  //4kb
        int read;
        //从文件中读入数据并写到输出字节流中
        while ((read = in.read(buff)) != -1) {
            stream.write(buff, 0, read);
        }
        stream.flush();
        stream.close();
        in.close();
        response.flushBuffer();
    }

    @RequestMapping("/root/property")
    public void fetchPropertyConfig(@RequestParam("filename") String fileName,
                                    @RequestParam("key") String key,
                                    HttpServletResponse response) throws IOException {
        if (key == null || key.isEmpty()) {
            return;
        }
        if (fileName == null || fileName.isEmpty()) {
            return;
        }
        File file = ResourceUtils.getFile("classpath:" + fileName + ".properties");
        Reader in = new InputStreamReader(new FileInputStream(file), "UTF-8");
        Properties prop = new Properties();
        prop.load(in);
        String result = prop.getProperty(key);
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(result);
        in.close();
        response.flushBuffer();
    }
}
